#
# USAGE:
#
# python compare_asr_dat_files.py [<id> <dat filepath> . . .]
#
# CREATES THESE FILES:
unaligned_fasta_path = "ancestors.unaligned.fasta"
#

import sys
import re

# asrpp_proportion is a hashtable, where key = ASR PP bin, value = proportion of sites with that PP
def barplot_in_r(asrpp_proportion, output_file_seed):
    bins = asrpp_proportion.keys()
    bins.sort()

    string = "props<-c("
    for asrpp in bins:
        string += asrpp_proportion[asrpp].__str__() + ","   
    string = re.sub(",$", "", string)
    string += ");\n"
    string += "barplot(props, xlab=\"P(a|t,m)\", ylab=\"proportion\", space=c(1.5,0), ylim=range(0,1.0), col=c(\"#0099ff\"));\n"
    
    fout_cran = open(output_file_seed + ".cran", "w")
    fout_cran.write("pdf('" + output_file_seed + ".pdf', width=7, height=3);\n")
    fout_cran.write(string)
    fout_cran.write("dev.off();\n")
    fout_cran.close()
    
    os.system("r --no-save < " + output_file_seed + ".cran")
    
#
# Capture command-line parameters
#
dat_files = {} # key = unique name, value = path to .dat file
i = 1
while i < sys.argv.__len__():
    name = sys.argv[i]
    i+= 1
    path = sys.argv[i]
    dat_files[name] = path
    i += 1
    print name, path

#
# Write a FASTA file with all the sequences
#
fasta_sequences = {} # key = unique name, value = string with sequence
for dat in dat_files:
    fasta_sequences[dat] = ""
    fin = open(dat_files[dat], "r")
    for line in fin.readlines():
        line = line.strip()
        tokens = line.split()
        fasta_sequences[ dat ] += tokens[1]
    fin.close()
fout = open(unaligned_fasta_path, "w")
for f in fasta_sequences:
    fout.write( ">" + f + "\n")
    fout.write( fasta_sequences[f] + "\n" )
fout.close()



